package com.pic4493.app;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.R.integer;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.fortysevendeg.swipelistview.BaseSwipeListViewListener;
import com.fortysevendeg.swipelistview.SwipeListView;
import com.pic4493.adapter.AdpGrid_Subscribe;
import com.pic4493.adapter.AdpList_Message;
import com.pic4493.base.BaseUITopBar;
import com.pic4493.comm.Session;
import com.pic4493.entities.DJson;
import com.pic4493.entities.EMessage;
import com.pic4493.entities.ESubscribe;
import com.pic4493.net.NetClientJ;
import com.pic4493.utils.UtiDialog;
import com.pic4493.utils.UtiUI;

public class UIMessages extends BaseUITopBar
{
   private SwipeListView mSwipeListView;
   private LinearLayout mLayEmpty;
   private AdpList_Message mAdpMessage;
   private ArrayList<EMessage> mList;
   private PopupWindow mPopupWindow;

   private void initView()
   {
	  mLayEmpty = (LinearLayout) findViewById(R.id.uimessage_lay_empty);

	  mSwipeListView = (SwipeListView) findViewById(R.id.uimessage_list);
	  mSwipeListView.setSwipeMode(SwipeListView.SWIPE_MODE_LEFT);
	  mSwipeListView.setSwipeActionLeft(SwipeListView.SWIPE_ACTION_REVEAL);
	  mSwipeListView.setOffsetLeft(UtiUI.getInstance().getScreenWidth()-UtiUI.dip2px(mContext, 150));// 控件左边两个按钮宽度一共120dp
	  mSwipeListView.setAnimationTime(0);
	  mSwipeListView.setSwipeOpenOnLongPress(false);
   }

   private void initEvent()
   {

   }

   private void initData()
   {
	  executeAsyncTask("loadData");
   }

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  setContentView(R.layout.uimessage);
	  super.onCreate(savedInstanceState);
	  setTitle("消息");

	  initView();
	  initEvent();
	  initData();
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  UtiDialog.getInstance().ShowLoadingDialogNoTitleEX(mContext, "请稍候");
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  if ("loadData".equals(taskName))
	  {
		 return NetClientJ.GetMessagesByUserId();
	  }
	  else if ("reply".equals(taskName))
	  {
		 return NetClientJ.ReplyMessage(params[0].toString(), params[1].toString(), params[2].toString());
	  }
	  else if ("del".equals(taskName))
	  {
		 return NetClientJ.DeleteMessageByMessageId(params[0].toString());
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  UtiDialog.getInstance().DismissLoadingDialog();
	  try
	  {
		 if (result != null)
		 {
			DJson data = (DJson) result;
			if (!data.getHead().hasError())
			{
			   if (taskName.equals("loadData"))
			   {
				  JSONArray messages = data.getBody().optJSONArray("message");
				  if (messages != null && messages.length() > 0)
				  {
					 mLayEmpty.setVisibility(View.GONE);
					 mSwipeListView.setVisibility(View.VISIBLE);

					 mList = new ArrayList<EMessage>();
					 EMessage ms = null;
					 for (int i = 0; i < messages.length(); i++)
					 {
						ms = new EMessage();
						ms.setId(messages.optJSONObject(i).optString("mid"));
						ms.setTime(messages.optJSONObject(i).optString("sendtime"));
						ms.setTitle(messages.optJSONObject(i).optString("title"));
						ms.setContent(messages.optJSONObject(i).optString("message"));
						mList.add(ms);
					 }

					 mAdpMessage = new AdpList_Message(mContext, mList, new AdpList_Message.OnClickEvent()
					 {
						@Override
						public void Reply(int position, View v)
						{
						   showReviewPopupWindow(((EMessage) mAdpMessage.getItem(position)).getId());
						}

						@Override
						public void Delete(int position, View v)
						{
						   executeAsyncTask("del", new Object[] { ((EMessage) mAdpMessage.getItem(position)).getId(),position });
						}
					 });
					 mSwipeListView.setAdapter(mAdpMessage);
				  }
				  else
				  {
					 mLayEmpty.setVisibility(View.VISIBLE);
					 mSwipeListView.setVisibility(View.INVISIBLE);
				  }
			   }
			   else if ("reply".equals(taskName))
			   {
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "回复成功");
				  mPopupWindow.dismiss();
			   }
			   else if ("del".equals(taskName))
			   {
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "删除成功");
				  int position=Integer.valueOf(params[1].toString());
				  mSwipeListView.closeAnimate(position);
				  mSwipeListView.dismiss(position);
				  mAdpMessage.removeItem(position);
				  mAdpMessage.notifyDataSetChanged();
//				  mSwipeListView.dismissSelected();
			   }
			}
			else
			{
			   UtiDialog.getInstance().ShowToastInfoShort(mContext, data.getHead().getRspMsg());
			}
		 }
		 else
		 {
			UtiDialog.getInstance().ShowToastInfoShort(mContext, "网络异常请稍候再试");
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UIMessages_onAsyncTaskEnd(taskId, taskName, params, result) " + e);
	  }
   }

   class MyListItemListener extends BaseSwipeListViewListener
   {

	  @Override
	  public void onClickFrontView(int position)
	  {
		 super.onClickFrontView(position);
	  }

	  @Override
	  public void onDismiss(int[] reverseSortedPositions)
	  {

	  }
   }

   public void showReviewPopupWindow(final String mid)
   {
	  try
	  {
		 LayoutInflater mInflater = LayoutInflater.from(mContext);
		 View popView = mInflater.inflate(R.layout.uimessage_pop_reply, null);
		 Button btnOK = (Button) popView.findViewById(R.id.uimessage_pop_btn_ok);
		 Button btnCancel = (Button) popView.findViewById(R.id.uimessage_pop_btn_cancel);
//		 TextView txt = (TextView) popView.findViewById(R.id.uimessage_pop_reply_txt);
		 final EditText edtContent = (EditText) popView.findViewById(R.id.uimessage_pop_edt);

		 btnOK.setOnClickListener(new View.OnClickListener()
		 {
			@Override
			public void onClick(View v)
			{
			   if (edtContent.getText().toString().trim().equals(""))
			   {
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "评论内容不能为空");
			   }
			   else
			   {
				  executeAsyncTask("reply", new Object[] { mid, edtContent.getText().toString().trim(), Session.getInstance().getUser().getNickName() });
			   }
			}
		 });
		 btnCancel.setOnClickListener(new View.OnClickListener()
		 {
			@Override
			public void onClick(View v)
			{
			   mPopupWindow.dismiss();
			}
		 });

		 mPopupWindow = new PopupWindow(popView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		 mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		 mPopupWindow.setAnimationStyle(R.style.Anim_Popup);
		 mPopupWindow.setFocusable(true);
		 mPopupWindow.setOutsideTouchable(true);
		 mPopupWindow.showAtLocation(mSwipeListView, Gravity.BOTTOM | Gravity.CENTER, 0, UtiUI.getInstance().getScreenHeight() / 2);
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UtiMenu_ShowReviewPopupWindow(conte1xt) " + e);
	  }
   }
}
